﻿namespace Probel.Client.Commands
{
    using System;
    using System.ComponentModel;
    using System.Configuration;
    using System.Net;
    using System.Xml.Serialization;

    using Probel.Client.RestEntities;

    [Command("rest","r","Displays usage statistics using the REST interface.")]
    public class RestCommand : ICommand
    {
        #region Methods

        public void Execute(dynamic context)
        {
            var url = ConfigurationManager.AppSettings["GetApplicationsSummary"];

            var serializer = new XmlSerializer(typeof(ApplicationsSummaryRest));
            Console.Write("Getting statistics (REST)...");
            using (var client = new WebClient())
            using (var stream = client.OpenRead(url))
            {
                var stats = (ApplicationsSummaryRest)serializer.Deserialize(stream);
                Console.WriteLine(" Done");

                Display(stats);
            }
        }

        private void Display(ApplicationsSummaryRest stats)
        {
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Statistics (application count): ");
            Console.ResetColor();
            Console.WriteLine();
            Console.WriteLine("nDoctor light: {0,-3}", stats.LdocCount);
            Console.WriteLine("      nDoctor: {0,-3}", stats.NDoctorCount);
            Console.WriteLine("        Other: {0,-3}", stats.OtherCount);
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Windows versions:");
            Console.ResetColor();
            Console.WriteLine();

            int i = 0;
            foreach (var version in stats.WindowsVersions)
            {
                Console.WriteLine("   {0,-2} - {1,5} item(s) of '{2}'", ++i, version.Count, version.Name);
            }
        }

        #endregion Methods
    }
}